import checrtsmenu from "@/assets/imgs/checrtsmenu.png";
import "./index.model.css";
import {
  Pagination,
  ConfigProvider,
  Table,
  Tooltip,
  message,
  Space,
  Button,
  Modal,
} from "antd";
import zhCN from "antd/es/locale/zh_CN";
import type { TableProps } from "antd";
import {
  useEffect,
  useState,
  useCallback,
  useRef,
  useLayoutEffect,
} from "react";
import { useAntdColumnResize } from "react-antd-column-resize";
import type { typesitem, EventItem, field } from "@/api/Home/type";
import {
  fetchEventList,
  eventTypes,
  eventClose,
  eventDel,
} from "@/api/Home/home";
import { useNavigate } from "react-router";

const ROW_HEIGHT = 55; // 每行高度近似值（用于计算）
const TABLE_HEADER_APPROX = 54; // 表头高度近似值（用于计算）

const EchartsTable = () => {
  const [typesList, setTypesList] = useState<typesitem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [columns, setColumns] = useState<TableProps<EventItem>["columns"]>([]);
  const [dataList, setDataList] = useState<EventItem[]>([]);

  const [selectedType, setSelectedType] = useState<string>("");

  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [totalCount, setTotalCount] = useState<number>(0);

  const [tableHeight, setTableHeight] = useState<number>(0);

  // 用来测量表格外层容器的 ref（用它的 clientHeight 作为可用高度基准）
  const tableWrapperRef = useRef<HTMLDivElement | null>(null);

  const navigate = useNavigate();

  // 操作列单独定义
  const operationColumn = {
    title: "操作",
    key: "action",
    align: "center",
    dataIndex: "action",
    fixed: "right",
    width: 120,
    ellipsis: {
      showTitle: false,
    },
    render: (_text: any, record: EventItem) => (
      <Space>
        <Button
          size="small"
          type="link"
          onClick={() => handleComplete([record.id])}
          style={{ color: "#00B6FB" }}
        >
          完成
        </Button>
        <Button
          size="small"
          type="link"
          style={{ color: "#00B6FB" }}
          onClick={() => handleDelete([record.id])}
        >
          删除
        </Button>
      </Space>
    ),
  };

  // 初始化获取事件类型
  useEffect(() => {
    const initialize = async () => {
      try {
        const res = await eventTypes();
        if (res.data?.length) {
          setTypesList(res.data);
          const firstTypeName = res.data[0].name;
          setSelectedType(firstTypeName);
          // 请求事件列表
          fetchEventListApi(firstTypeName, currentPage, pageSize);
        }
      } catch (error) {
        message.error("获取事件类型失败");
      }
    };
    initialize();
  }, []);

  useEffect(() => {
    if (selectedType) {
      fetchEventListApi(selectedType, currentPage, pageSize);
      setSelectedRowKeys([]);
    }
  }, [selectedType, currentPage, pageSize]);

  // 获取事件列表
  const fetchEventListApi = useCallback(
    async (typeName: string, page = 1, size = 6) => {
      try {
        const res = await fetchEventList(typeName, page, size);
        setDataList(res.data.results);
        setColumns(generateColumns(res.fields));
        setTotalCount(res.data.count);
      } catch (error) {
        console.error("请求事件列表失败:", error);
        message.error("获取事件列表失败，请稍后重试。");
      }
    },
    []
  );

  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 动态生成列
  const generateColumns = (fields: field[]) => {
    const dynamicCols = fields
      .filter((f) => f.istitle === 1)
      .map((f) => {
        const entries = Object.entries(f).filter(([k]) => k !== "istitle");
        const [key, title] = entries[0]; // 只取第一个有效键值对

        return {
          title,
          dataIndex: key,
          key,
          width: 100,
          ellipsis: { showTitle: false },
          render: (value: string) => (
            <Tooltip placement="topLeft" title={value}>
              {value}
            </Tooltip>
          ),
        };
      });

    // 添加操作列
    dynamicCols.push(operationColumn);

    return dynamicCols;
  };

  // 单个/批量完成
  const handleComplete = async (ids: (string | number)[]) => {
    if (!ids.length) {
      message.warning("请先选择数据");
      return;
    }
    try {
      const res = await eventClose({ id: ids });
      if (res.code === 1) {
        message.success(res.message || "事件完成成功");
        setSelectedRowKeys([]); // 清空选择
        fetchEventListApi(selectedType, currentPage, pageSize);
      } else {
        message.error(res.message || "完成失败");
      }
    } catch (error) {
      message.error("事件完成失败");
    }
  };

  // 单个/批量删除
  const handleDelete = (ids: (string | number)[]) => {
    if (!ids.length) {
      message.warning("请先选择数据");
      return;
    }
    Modal.confirm({
      title: "确认删除选中数据吗？",
      content: <p>删除后数据将不可恢复，请谨慎操作！</p>,
      okText: "确定",
      cancelText: "取消",
      async onOk() {
        try {
          const res = await eventDel({ id: ids.map(Number) });
          if (res.code === 1) {
            message.success(res.message || "删除成功");
            setSelectedRowKeys([]); // 清空选择
            fetchEventListApi(selectedType, currentPage, pageSize);
          } else {
            message.error(res.message || "删除失败");
          }
        } catch (err) {
          message.error("删除失败，请稍后重试。");
        }
      },
    });
  };

  // 重置
  const handleReset = () => {
    setSelectedType(typesList[0]?.name || "");
    setCurrentPage(1);
    setPageSize(10);
    setSelectedRowKeys([]);
  };

  // 刷新
  const handleRefresh = () => {
    fetchEventListApi(selectedType, currentPage, pageSize);
  };

  // 选中行变化
  const onRowSelectionChange = (keys: React.Key[]) => {
    setSelectedRowKeys(keys);
  };
  const handleRowDoubleClick = (record: EventItem) => {
    // 跳转并传递数据
    navigate("/echarts_table/echarts_process", { state: record.nodeflows });
  };

  // 列宽调整 hook
  const { resizableColumns, components, tableWidth } =
    useAntdColumnResize(() => {
      return { columns };
    }, [columns]);

  // =========== 自适应高度计算逻辑 ===========
  const calcTableHeight = useCallback(() => {
    const wrapper = tableWrapperRef.current;
    if (!wrapper) return;

    // 计算 wrapper 可用高度（去掉 padding）
    const style = getComputedStyle(wrapper);
    const paddingTop = parseFloat(style.paddingTop || "0");
    const paddingBottom = parseFloat(style.paddingBottom || "0");
    const innerHeight = wrapper.clientHeight - paddingTop - paddingBottom;

    // 表格 body 的最大可用高度（避免 header 被遮盖）
    const maxBodyAvailable = Math.max(innerHeight - TABLE_HEADER_APPROX, 80);

    // 期望的 body 高度 = 每行高度 * pageSize，但不超过容器能提供的最大高度
    const desiredBody = Math.min(ROW_HEIGHT * pageSize, maxBodyAvailable);

    setTableHeight(Math.floor(desiredBody));
  }, [pageSize]);

  // 在布局阶段尽快测量（避免闪烁），当 pageSize / 列 / 数据长度 改变时重新计算
  useLayoutEffect(() => {
    calcTableHeight();
  }, [calcTableHeight, dataList.length, columns]);

  // 窗口大小改变时重新计算
  useEffect(() => {
    const onResize = () => requestAnimationFrame(calcTableHeight);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, [calcTableHeight]);

  // =========== end 自适应高度计算逻辑 ===========

  return (
    <div className="text-white flex flex-col h-full">
      <div className="relative w-full">
        <img src={checrtsmenu} alt="" />
        <div className="absolute w-full left-0 top-1/10 -translate-y-1/2  pl-24 pr-24 flex items-center justify-between text-white">
          <div className="text-xl font-bold">调度人工介入事件清单</div>
          <div className="flex">
            <button className="echarts-button-style" onClick={handleReset}>
              重置
            </button>
            <button className="echarts-button-style" onClick={handleRefresh}>
              刷新
            </button>
            <button
              className="echarts-button-style"
              onClick={() => handleComplete(selectedRowKeys)}
            >
              批量完成
            </button>
            <button
              className="echarts-button-style"
              onClick={() => handleDelete(selectedRowKeys)}
            >
              批量删除
            </button>
          </div>
        </div>
      </div>
      <div className="flex m-5 items-center justify-between gap-5">
        {typesList.map((item, index) => (
          <div
            key={index}
            className={`w-full cursor-pointer relative p-4 flex items-center justify-between text-white ${
              selectedType === item.name
                ? "bg-[rgba(0,0,0,0.3)]"
                : "bg-[rgba(0,0,0,0.1)]"
            } corner-box`}
            onClick={() => {
              setSelectedType(item.name);
              setCurrentPage(1);
              fetchEventListApi(item.name, 1, pageSize);
            }}
          >
            <div className="text-[#fff] font-bold whitespace-nowrap">{item.name}</div>
            <div className="text-[#FFF] bg-[#3a3e43] rounded-16 pl-3 pr-3 border border-[rgba(0,0,0,0.3)]">
              {item.active}/{item.total}
            </div>
            <div className="corner-bottom-left"></div>
            <div className="corner-bottom-right"></div>
          </div>
        ))}
      </div>

      {/* 给这个容器加 ref，用它的 clientHeight 作为计算基准 */}
      <div
        ref={tableWrapperRef}
        className="inner-table tableColor scrollItemBox ml-5 mr-5 corner-box flex-1 h-full bg-[rgba(0,0,0,0.1)]"
      >
        <Table
          rowKey="id"
          rowSelection={{
            selectedRowKeys,
            onChange: onRowSelectionChange,
          }}
          columns={resizableColumns}
          dataSource={dataList}
          components={components}
          size="small"
          scroll={{ y: tableHeight }}
          pagination={false}
          locale={{
              emptyText: <div className="text-gray-500 py-6">暂无数据</div>,
            }}
          onRow={(record) => ({
            onDoubleClick: () => {
              handleRowDoubleClick(record);
            },
          })}
        />
        <div className="corner-bottom-left"></div>
        <div className="corner-bottom-right"></div>
      </div>

      <div className="mt-[auto] flex justify-end">
        <ConfigProvider
          locale={zhCN}
          theme={{
            token: {
              colorText: "#fff", // 全部文字白色
            },
            components: {
              Select: {
                optionSelectedBg: "#4a4f55",
                optionActiveBg: "#4a4f55",
                colorBgContainer: "#4a4f55",
                colorText: "#fff",
              },
              Pagination: {
                itemBg: "transparent",
                itemActiveBg: "#236bff",
                colorText: "#fff",
                colorPrimary: "#236bff",
              },
            },
          }}
        >
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={totalCount}
            showSizeChanger
            pageSizeOptions={["10", "20", "30"]}
            showTotal={(total, range) =>
              `第 ${range[0]}-${range[1]} 条 / 共 ${total} 条`
            }
            onChange={handlePageChange}
          />
        </ConfigProvider>

        <style>{`
         .ant-pagination-item {
           border: none !important;
           background: transparent !important;
           color: #fff !important;
         }
         .ant-pagination-item-active {
           background: rgba(0,0,0,0.3) !important;
           border-radius: 50% !important;
           color: #fff !important;
           border: none !important;
         }
         .ant-pagination-item-active a {
           color: #fff !important;
         }
         .ant-pagination-prev .ant-pagination-item-link,
         .ant-pagination-next .ant-pagination-item-link {
           background: rgba(0,0,0,0.3) !important;
           color: #fff !important;
           border: none !important;
           border-radius: 4px;
         }
         .ant-pagination-item-ellipsis {
           color: #fff !important;
         }
         .ant-select-dropdown {
           background: #0f192d !important;
         }
        `}</style>
      </div>
    </div>
  );
};
export default EchartsTable;
